import cn.icyzx.models.User;
import net.sf.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by zk on 2016/10/20.
 */
public class test {

    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        User user = new User();
        user.setUid("123");
        user.setPassword("123");
        System.out.println(beanToJsonObject(user));
    }

    public static <T> JSONObject beanToJsonObject(T t) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        JSONObject jsonObject = new JSONObject();
        Class<?> clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String getMethod = "get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1, field.getName().length());
            Method method = clazz.getMethod(getMethod);
            jsonObject.put(field.getName(), method.invoke(t, null));
        }

        return jsonObject;
    }
}